<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link rel="stylesheet" href="../../res/layui/css/layui.css" media="all">
		<link rel="stylesheet" href="../../res/css/common/font-awesome.min.css" media="all">
		<link rel="stylesheet" href="../../res/layui-config/css/app.css" media="all">
		<title>药品管理</title>
		<script type="text/javascript" src="../../res/js/common/session.js"></script>
	</head>
	<body>
		<!-- <select name="comName" lay-filter="mat-type" id="mat-type">
				<option value="">店铺选择</option>
		</select> -->
		<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
		  <legend>增加批发订单</legend>
		</fieldset>
		<div class="layui-form">
		  <table class="layui-table"  style="width:880px;" lay-filter="test3" id="add">
			  <thead>
			    <tr>
			      <th lay-data="{field:'id', width:150, sort: true, edit: 'text'}">药品名称</th>
			      <th lay-data="{field:'username', width:100, sort: true, edit: 'text'}">药品类型</th>
			      <th lay-data="{field:'email', edit: 'text', width:50}">零售价格</th>
			      <th lay-data="{field:'sex', width:50, edit: 'text'}">数量</th>
			      <th lay-data="{field:'city', edit: 'text', width:50}">小计</th>
			      <th lay-data="{field:'city', edit: 'text', width:50}">批发价</th>
			      <th lay-data="{fixed: 'right',title: '操作',width: 180,align: 'center',toolbar: '#barDemo'}">操作</th>
			    </tr>
			  </thead>
			</table>
		</div>
		<button onclick="okpi()" style="position:absolute;top:38px;left:780px;width:100px;" class="layui-btn layui-btn-sm kit-btn">确认批发</button>
		<div id="zong" style="margin-top: 30px;">
			总金额:<input id="zongjin" style="width:120px;display: inline-block" disabled class="layui-input" type="text" />
			 总数量:<input id="zongshu" style="width:120px;display: inline-block" disabled class="layui-input" type="text" />
		</div>
		<div class="kit-table">
		    <form class="layui-form" lay-filter="kit-search-form">
				<!-- 左上角的两个按钮 -->
		        <div class="kit-table-header">
		            <div style="left:30px;" class="kit-search-inputs">
		                <div class="kit-search-keyword">
		                    <input type="text" class="layui-input" id="serach-one" placeholder="药品.." onKeyUp="lockInput(this,'serach-two')"/>
		                    <button style="left:170px;" lay-submit lay-filter="search"><i class="layui-icon">&#xe615;</i></button>
		                </div>
		                <div style="left:230px;" class="kit-search-more" id="kit-search-more">更多筛选<i class="layui-icon">&#xe61a;</i></div>
		            </div>
		        </div>
				<!-- 搜索扩展工具条 -->
		        <div class="kit-search-mored layui-anim layui-anim-upbit">
		            <div class="kit-search-body">
		                <div class="layui-form-item">
		                    <label class="layui-form-label">药品名称</label>
		                    <div class="layui-input-block">
		                        <input type="text" name="drugName" id="serach-two" placeholder="搜索关键字.." autocomplete="off" class="layui-input" onKeyUp="lockInput(this,'serach-one')">
		                    </div>
		                </div>
		                <div class="layui-form-item">
			                <label class="layui-form-label">类型</label>
			                <div class="layui-input-block">
			                    <select name="dtId" id="drug-type">
			                      <option value=""></option>
			                    </select>
			                </div>
		                </div>
		                <div class="layui-form-item">
			                <label class="layui-form-label">店铺</label>
			                <div class="layui-input-block">
			                     <select name="comId" lay-filter="mat-type" id="mat-type">
									<option value="">店铺选择</option>
								</select>
			                </div>
		                </div>
		                <div class="layui-form-item">
		                    <div class="layui-inline">
		                        <label class="layui-form-label">范围</label>
		                        <div class="layui-input-block">
			                        <div class="layui-input-inline" style="width: 100px;">
			                            <input type="text" name="priceMin" placeholder="￥" autocomplete="off" class="layui-input" maxlength="6" onKeyUp="amount(this)">
			                        </div>
			                        <div class="layui-form-mid">-</div>
			                        <div class="layui-input-inline" style="width: 100px;">
			                            <input type="text" name="priceMax" placeholder="￥" autocomplete="off" class="layui-input" maxlength="6" onKeyUp="amount(this)">
			                        </div>
		                        </div>
		                    </div>
		                </div>
		            </div>
		            <div class="kit-search-footer">
		                <button type="reset" class="layui-btn layui-btn-sm layui-btn-primary kit-btn reset-btn">重置</button>
		                <button lay-submit lay-filter="search" class="layui-btn layui-btn-sm kit-btn">确定</button>
		            </div>
		        </div>
		    </form>
			<!-- 操作按钮 -->
		    <div class="kit-table-body">
		        <table id="demo" lay-filter="demo"></table>
		        <script type="text/html" id="barDemo">
		            <button class="layui-btn layui-btn-xs" lay-event="detail">添加到清单</button>
		        </script>
		    </div>
		</div>
		
		<!-- 修改页面 -->
		<script type="text/html" id="edit-tpl">
		    	
		</script>
		<script src="../../res/js/common/jquery-1.11.2.min.js"></script>
		<script>
			//文本框只能输入金额
		    function amount(th){
		        var regStrs = [
		            ['^0(\\d+)$', '$1'], //禁止录入整数部分两位以上，但首位为0
		            ['[^\\d\\.]+$', ''], //禁止录入任何非数字和点
		            ['\\.(\\d?)\\.+', '.$1'], //禁止录入两个以上的点
		            ['^(\\d+\\.\\d{2}).+', '$1'] //禁止录入小数点后两位以上
		        ];
		        for(i=0; i<regStrs.length; i++){
		            var reg = new RegExp(regStrs[i][0]);
		            th.value = th.value.replace(reg, regStrs[i][1]);
		        }
		    }
			//搜索框同步输入
			function lockInput(obj,id){
				$("#"+id).val($(obj).val());
			}
		</script>
		<script src="../../res/layui/layui.all.js"></script>
		<script>
			//显示表格数据
			 var tableElem="";
		    layui.use(['table','upload'], function() {
		        var table = layui.table,
		            $ = layui.jquery,
		            layer = layui.layer,
		            form = layui.form,
		            laytpl = layui.laytpl;
		        var admin = getSession("../../");
		        var tableIns = table.render({
		            elem: '#demo',
		            height: '475px', //容器高度
		            url: '../../drug/showList.action',
		            where:{"comId":admin.comId},
		            page: true,
		            id: 'demo',
		            cols: [
		                [{field: 'drugName',title: '药名',width: 175},
		                {field: 'dtName',title: '类型',width: 80},
		                {field: 'drugPictrue',title: '图片',width: 60,templet:'<div><img style="height:100%;height:30px;" src="../../{{ d.drugPictrue}}"></div>'},
		                {field: 'drugPrice',title: '价格（元）',width: 150,sort: true},
		                {field: 'diAmount',title: '库存',width: 150,sort: true},
		                {fixed: 'right',title: '操作',width: 180,align: 'center',toolbar: '#barDemo'}]
		            ],
		            done: function(res, curr, count) {
		            	tableElem=this.elem.next('.layui-table-view');
		                $("[data-field = 'drugProp']").children().each(function(){
						    if($(this).text() == '1'){
						    	$(this).text("处方药");
						    } else if ($(this).text() == '0') {
						    	$(this).text("非处方药");
						    }
					  	});
		            },
		            loading: true
		        });
				//查询类型下拉框数据
		        var staticData = null;
		        $.ajax({ url:"../../drugType/showList.action",
                    type:'post',//method请求方式，get或者post
                    cache: false,//同步
                    dataType:'json',//预期服务器返回的数据类型
                    success:function(mes){//res为相应体,function为回调函数
                    	//增加及修改类型下拉框内的数据
                    	staticData = mes;
                    	//循环添加类型搜索框内的数据
                    	$.each(mes.types,function(index,item){
                    		$("#drug-type").append("<option value="+item.dtId+">"+item.dtName+"</option>");
                    	});
                    	//渲染类型搜索框内的下拉框
                    	renderForm();
                    }
                 });
		        var staticData = null;
		        $.ajax({ 
		        	url:'../../company/findAll.action',
                    type:'post',//method请求方式，get或者post
                    cache: false,//同步
                    dataType:'json',//预期服务器返回的数据类型
                    success:function(mes){//res为相应体,function为回调函数
                    	//增加及修改类型下拉框内的数据
                    	staticData = mes;
                    	//循环添加类型搜索框内的数据
                    	$.each(mes.data,function(index,item){
                    		$("#mat-type").append("<option value="+item.comId+">"+item.comName+"</option>");
                    	});
                    	//渲染类型搜索框内的下拉框
                    	renderForm();
                    }
                 });
		       
		        var zongj=0.00;
		        var zongshu=0;
		        table.on('checkbox(demo)', function(obj){
		        	var data = obj.data; //获得当前行数据
		            var layEvent = obj.event; //获得 lay-event 对应的值
		            var tr = obj.tr; //获得当前行 tr 的DOM对象
		        	if(obj.checked==true){
		        		//价格
		        		var mony = data.drugPrice;
			        	$("#add").append("<tr><td style='display:none'>"+data.drugId+"</td><td>"+data.drugName+"</td><td>"+data.dtName+"</td><td id='pic_"+data.drugId+"'>"+data.drugPrice+"</td><td><input type='text' id='up_"+data.drugId+"' class='numbers' style='height:20px; border:0px; width:80px;' onKeyUp='num(this)' value='1' /></td><td id='zong_"+data.drugId+"'></td><td id='pi_"+data.drugId+"'></td><td><button onclick=\"changeState(this,\'"+data.drugId+"\')\">删除</button></td></tr>");
			        	//数量
			        	var num=$(".numbers").val();
			        	//赋值总价
			        	$("#zong_"+data.drugId+"").text(parseFloat(mony*num).toFixed(2));
			        	
			        	var pi=parseFloat((mony*num)*0.8).toFixed(2);
			        	$("#pi_"+data.drugId+"").text(pi);
			        	zongj+=parseFloat(pi);
			        	
			        	var shu=$("#up_"+data.drugId+"").val();
			        	zongshu+=parseFloat(shu);
		        	}
		        	$("#zongjin").val(zongj.toFixed(2));
		        	$("#zongshu").val(zongshu);
		        });

		        $('body').on('click', '.del', function() { 
		        		$(this).closest('tr').remove();
						var zongmoney=0.0;
						var zongnum=0;
		        		$("#add tr").not(":first").each(function(){
							var shu=parseInt($(this).find('td:eq(4) input').val());
							var pijia=parseFloat($(this).find('td:eq(6)').text()).toFixed(2);
							zongmoney+=pijia;
							zongnum+=shu;
						});
		        		$("#zongshu").val(zongnum);
						$("#zongjin").val(zongmoney);
		        	});
		      	 //监听搜索表单提交
		        form.on('submit(search)', function(data) {
		            //带条件查询
		            tableIns.reload({
		                where: data.field,
		                page: { curr: 1 }
		            });
		            $('.kit-search-mored').hide();
		            return false;
		        });
		        
		        //渲染 修改和增加弹出层
			    function showlayer(d){
			    	laytpl($('#edit-tpl').html()).render(d,function(html) {
	                    layer.open({
	                        type: 1,
	                        title: '表单',
	                        content: html,
	                        area: ['800px', '430px'],
	                        btn: ['提交', '重置', '取消'],
	                        yes: function(index, layero) {
	                            editIndex = index;
	                            $('form[lay-filter="form-edit"]').find('button[lay-submit]').click();
	                        },
	                        btn2: function(index, layero) {
	                            $('form[lay-filter="form-edit"]').find('button[type="reset"]').click();
	                            return false;
	                        },
	                        success: function() {
	                            form.render(null, 'form-edit');
	                        }
	                     });
	                    upload();
	                });
			    }
		        //监听工具条按钮点击
		        table.on('tool(demo)', function(obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
		            var data = obj.data; //获得当前行数据
		            var layEvent = obj.event; //获得 lay-event 对应的值
		            var tr = obj.tr; //获得当前行 tr 的DOM对象
					var blean=true;
		            if (layEvent === 'detail') { //查看
							$("[data-field = 'drugName']").children().not(":first").each(function(index){
	            				var m=tableElem.find("tr[data-index="+index+"]").find("button").attr('disabled'); 
								if(data.drugName==$(this).text() && m==null){
	            					 tableElem.find("tr[data-index="+index+"]").find("button").addClass('layui-btn-disabled').attr('disabled',true);
	            					 var mony = data.drugPrice;
	     			            	$("#add").append("<tr><td style='display:none'>"+data.drugId+"</td><td>"+data.drugName+"</td><td>"+data.dtName+"</td><td id='pic_"+data.drugId+"'>"+data.drugPrice+"</td><td><input type='text' id='up_"+data.drugId+"' class='numbers' style='height:20px; border:0px; width:80px;' onblur='num(this)' value='1' /></td><td id='zong_"+data.drugId+"'></td><td id='pi_"+data.drugId+"'></td><td><button onclick=\"changeState(this,\'"+data.drugId+"\')\">删除</button></td><td style='display:none'>"+data.diAmount+"</td></tr>");
	     			            	//数量
	     				        	var num=$(".numbers").val();
	     				        	//赋值总价
	     				        	$("#zong_"+data.drugId+"").text(parseFloat(mony*num).toFixed(2));
	     				        	
	     				        	var pi=parseFloat((mony*num)*0.8).toFixed(2);
	     				        	$("#pi_"+data.drugId+"").text(pi);
	     				        	zongj+=parseFloat(pi);
	     				        	
	     				        	var shu=$("#up_"+data.drugId+"").val();
	     				        	zongshu+=parseFloat(shu);
	     				        	
	     				        	$("#zongjin").val(zongj.toFixed(2));
	     			        		$("#zongshu").val(zongshu);
	     			        		
	     			        		
	     			        		var zongmoney=0.00;
	     							var zongnum=0;
	     			        		$("#add tr").not(":first").each(function(){
	     								zongnum+=parseInt($(this).find('td:eq(4) input').val());
	     								zongmoney+=parseFloat($(this).find('td:eq(6)').text());
	     							});
	     			        		$("#zongshu").val(zongnum);
	     							$("#zongjin").val(zongmoney.toFixed(2));
	            				 }	
	        				 });
		        	}
		        });
		        //表单渲染
		        form.render(null, 'kit-search-form');
		        //更多筛选点击事件
		        $('#kit-search-more').on('click', function() {
		            $('.kit-search-mored').toggle();
		        });
		    });
		  	//重新渲染表 单
		  	function renderForm(){ 
	  			layui.use('form', function(){ 
		  			var form = layui.form;//高版本建议把括号去掉，有的低版本，需要加() 
		  			form.render(); 
	  			});  
	  		}
		  	
		  
		  	
		  	 function changeState(obj,rwowId) {
		  		 	var str=$(obj).parent().prev().prev().prev().prev().prev().prev().text();
		  		 
		  			$(obj).closest('tr').remove();
		 			var zongmoney=0.00;
					var zongnum=0;
					
					var strs=null;
	        		$("#add tr").not(":first").each(function(index){
	        			zongnum+=parseInt($(this).find('td:eq(4) input').val());
						zongmoney+=parseFloat($(this).find('td:eq(6)').text());
					});
	        			
	        		$("[data-field = 'drugName']").children().not(":first").each(function(index){
	            		 if($(this).text()==str){
	        	        	tableElem.find("tr[data-index="+index+"]").find("button").removeClass('layui-btn-disabled');
	        	        	tableElem.find("tr[data-index="+index+"]").find("button").removeAttr('disabled');
	            		}	
	        		 });
	        		$("#zongshu").val(zongnum);
					$("#zongjin").val(zongmoney);
		 	}
		  	 
		    //ajax加载动画
		    $(function () {
	            $.ajaxSetup({
	                layerIndex:-1,
	                beforeSend: function () {
	                    this.layerIndex = layer.load(1, { shade: [0.8, '#ffffff'] });
	                },
	                complete: function () {
	                    layer.close(this.layerIndex);
	                },
	                error: function () {
	                    layer.alert('部分数据加载失败，可能会导致页面显示异常，请刷新后重试', {
	                        skin: 'layui-layer-molv'
	                       , closeBtn: 0
	                       , shift: 4 //动画类型
	                    });
	                }
	            });
	        });
		</script>
		<script type="text/javascript">
		function num(obj){
			$("#zongjin").val("");
			var id = obj.id;
			var a = obj.value;
			var kucun=$(obj).parent().next().next().next().next().text();
			var reg= /^[1-9]\d*$/gi;
			
			if (reg.test(a)) {
				if(a<=parseInt(kucun)){
					if(a!=""&&a!=0){
						
						
						var b=$(obj).parent().prev().text();
						var c =parseFloat(a).toFixed(2)*parseFloat(b).toFixed(2);
						var d=c*0.8;
						$(obj).parent().parent().children().eq(5).text(c);
						$(obj).parent().parent().children().eq(6).text(parseFloat(d).toFixed(2));
						
						var zongmoney=0.0;
						var zongnum=0;
						$("#add tr").not(":first").each(function(){
							zongmoney+=parseFloat($(this).find('td:eq(4) input').val());
							zongnum+=parseInt($(this).find('td:eq(6)').text());
						});
						
						$("#zongshu").val(zongmoney);
						$("#zongjin").val(zongnum.toFixed(2));
					}else{
						resultshu(obj);
					}
				}else{
					layer.alert('库存不足,还剩:'+kucun+" 盒");
					resultshu(obj);
				}
			}else{
				layer.alert('只能输入数字');
				resultshu(obj);
			}
		}
		
		function resultshu(obj){
			obj.value="1";
			
			var cm=obj.value;
			var b=$(obj).parent().prev().text();
			var c =parseFloat(cm).toFixed(2)*parseFloat(b).toFixed(2);
			var d=c*0.8;
			
			$(obj).parent().parent().children().eq(5).text(c);
			$(obj).parent().parent().children().eq(6).text(parseFloat(d).toFixed(2));
			
			var zongmoney=0.0;
			var zongnum=0;
			$("#add tr").not(":first").each(function(){
				zongmoney+=parseFloat($(this).find('td:eq(4) input').val());
				zongnum+=parseInt($(this).find('td:eq(6)').text());
			});
			$("#zongshu").val(zongmoney);
			$("#zongjin").val(zongnum.toFixed(2));
		}
		
		function okpi(){
			var s=0;
			$("#add tr").not(":first").each(function(index){
				s++;
			});
			if(s!=0){
				var html="";
				$("#add tr").not(":first").each(function(){
					$(this).find("td").each(function(j){
						html+=$(this).text()+",";
					});
						html+=$(this).find('td:eq(4) input').val()+"#";
				});
				$.ajax({ url:"../../wholesale/Wholesalemanagement.action",
	                type:'post',//method请求方式，get或者post
	                cache: false,//同步
	                dataType:'json',//预期服务器返回的数据类型
	                data:{"htmlstr":html,"zongshu":$("#zongshu").val(),"zongjin":$("#zongjin").val(),"comIdname":$("#mat-type").val()},//传表格数据
	                success:function(mes){//res为相应体,function为回调函数
	                	 if(mes.msg>=1){
	                		 layer.msg('添加成功'); 
	                		 closeLayer();
	                		$("#zongshu").val("");
	         				$("#zongjin").val("");
	                	 }else{
	                		 layer.msg('添加失败'); 
	                	 }
	                }
	             });
			}else{
				layer.msg('请添加物品');
			}
		}
		
		function closeLayer(){
			history.go(0);location.reload();//返回上一页重载页面，本地刷新
		    //当你在iframe页面关闭自身时
			var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
			parent.layer.close(index); //再执行关闭   
			window.parent.location.reload(); // 父页面刷新
		}
		
		</script>
	</body>